import {
  Body,
  Controller,
  Delete,
  Get,
  Module,
  Param,
  Put,
  UseInterceptors,
} from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
import { ArticleModule } from "src/article/article.module";
import { ArticleService } from "src/article/article.service";
import { ArticleUpdateDTO } from "src/article/dto/article-update.dto";
import {
  ArticleDTODealError,
  DealtArticleDTO,
} from "src/article/interface/article-dealt";
import { WebResult } from "src/common/web.result";
import { AdminLoginInterceptor } from "src/admin/interceptor/alogin.interceptor";
import { UserModule } from "src/user/user.module";

@Controller("/admin/article")
@UseInterceptors(AdminLoginInterceptor)
export class AdminArticleController {
  constructor(
    private readonly prisma: PrismaClient,
    private readonly articleService: ArticleService,
  ) {}

  @Get("/view/count")
  async getArticleViewCount() {
    const count = await this.prisma.article_view.count();
    return WebResult.success(count);
  }

  @Put(["/", "/update"])
  async updateArticle(articleUpdateDTO: ArticleUpdateDTO) {
    if (!articleUpdateDTO.id) {
      return WebResult.failure(undefined, "缺少必要参数id");
    }
    try {
      const article = await this.prisma.article.findUnique({
        select: {
          publisher_id: true,
          sort_id: true,
          author: true,
          author_home_page: true,
          cover: true,
          title: true,
          date: true,
        },
        where: {
          id: articleUpdateDTO.id,
        },
      });
      if (!article) {
        return WebResult.failure(undefined, "不存在的文章");
      }

      const dealtDTO: DealtArticleDTO =
        await this.articleService.dealArticleDTO(articleUpdateDTO);
      await this.prisma.article.update({
        where: {
          id: articleUpdateDTO.id,
        },
        data: {
          sort_id: dealtDTO.sort_id || article.sort_id,
          author: dealtDTO.author || article.author,
          author_home_page:
            dealtDTO.author_home_page || article.author_home_page,
          cover: dealtDTO.cover || article.cover,
          title: dealtDTO.title || article.title,
          date: dealtDTO.date || article.date,
          content: dealtDTO.textContent,
        },
      });

      // 更新 ArticleContentData
      this.articleService.saveArticleContentData(
        {
          publisher_id: article.publisher_id,
          id: articleUpdateDTO.id,
        },
        dealtDTO.content_type,
        dealtDTO.content,
      );
      return WebResult.success(undefined, "更新成功");
    } catch (e) {
      console.error(e);
      if (e instanceof ArticleDTODealError) {
        return WebResult.failure(undefined, e.message);
      }
      return WebResult.failure(undefined, "内部错误");
    }
  }

  @Put(["/:id", "/update/:id"])
  async updateArticleByPathID(
    @Param("id") id: string,
    @Body() articleUpdateDTO: ArticleUpdateDTO,
  ) {
    const articleID = parseInt(id);
    if (isNaN(articleID)) {
      return WebResult.failure(undefined, "参数错误，删除失败");
    }
    articleUpdateDTO.id = articleID;
    return await this.updateArticle(articleUpdateDTO);
  }

  @Delete(["/:id", "/delete/:id"])
  async deleteArticleByPathID(@Param("id") id: string) {
    const articleID = parseInt(id);
    if (isNaN(articleID)) {
      return WebResult.failure(undefined, "article id must be a number");
    }
    let deleted = undefined;
    try {
      // 删除归档（一个文章可能有多个归档，所有要deleteMany）
      // await this.prisma.article_archive.deleteMany({
      //   where: {
      //     article_id: articleID,
      //   },
      // });
      // 删除浏览量记录
      // await this.prisma.article_view.delete({
      //   where: {
      //     article_id: articleID,
      //   },
      // });
      // 删掉点赞数据
      // await this.prisma.article_like.deleteMany({
      //   where: {
      //     article_id: articleID,
      //   },
      // });
      // 删除文章
      deleted = await this.prisma.article.delete({
        where: {
          id: articleID,
        },
      });
    } catch (e) {
      console.error(e);
      return WebResult.failure(undefined, "删除失败");
    }
    if (deleted) {
      this.articleService.deleteArticleContentDataFile(
        deleted.publisher_id,
        articleID,
      );
    }
    return WebResult.success(undefined, "删除成功");
  }
}

@Module({
  imports: [UserModule, ArticleModule],
  controllers: [AdminArticleController],
  providers: [],
  exports: [],
})
export class AdminArticleModule {}
